package my.jieh.test;

import idv.jieh.commons.sql.*;
import java.sql.*;
import java.io.*;

public class TryName extends idv.jieh.commons.comm.BasicClass{

  private SimpleConnection sc = new SimpleConnection();

  public TryName(){
    SimpleConnection.registerDriver("net.sourceforge.jtds.jdbc.Driver");
    sc.setProperty("user", "sa");
    sc.setProperty("password", "jieh817");

    Connection conn = sc.getConnection("jdbc:jtds:sqlserver://localhost:1433/");

    try {
      sc.useDatabase(conn, "target");
    }catch (SQLException ex) {
      dbr.exception(ex);
    }

    check(conn, query(conn));

  }

  private TableCache query(Connection conn){
    SQLMaker sm = new SQLMaker();
    sm.append("select Name_NVAR from Table_1");
//    sm.append("select Name_VAR from Table_2 where ischeck is null");
    TableCache tc = new TableCache();

    try {
      sm.generateTableCache(conn, tc);
    }catch (SQLException ex) {
      dbr.exception(ex);
    }

    return tc;
  }

  private void check(Connection conn, TableCache tc){
    for(int i=1, l=tc.size(); i<=l; i++){
      RowCache row = tc.getRow(i);
      String name = row.getValue("Name_NVAR");
      String word;
      for(char c : name.toCharArray()){
        if(isDoubleByte(c)){
          word = String.valueOf(c);
          insert(conn, word);
        }
      }
//      checkup(conn, name);
    }
  }


  private void insert(Connection conn, String word){
    dbr.normal(word);
    SQLMaker sm = new SQLMaker();
    sm.setValue(SQLMaker.STR, "utf8", word);

    /*
    String new_word = "?";
    try {
      new_word = String.valueOf(word.getBytes("big5"));
    }catch (UnsupportedEncodingException ex) {
      dbr.normal(word);
    }
    */

//    sm.setValue(SQLMaker.STR, "big5", word);

    try {
      sm.excuteInsert(conn, "Table_3");
    }catch (SQLException ex) {
      String msg = ex.getMessage();
      int idx = msg.indexOf("Violation of PRIMARY KEY constraint");
      if (idx == -1){
        dbr.exception(ex);
      }
    }

  }


  public boolean isDoubleByte(char c){
    return String.valueOf(c).getBytes().length == 2;
  }

/*
  public void checkup(Connection conn, String name){
    SQLMaker sm = new SQLMaker();
    sm.setValue(SQLMaker.STR, "ischeck", "Y");
    sm.appendWhere(SQLMaker.STR, "Name_VAR", name);
    try {
      sm.excuteUpdate(conn, "Table_2");
    }catch (SQLException ex) {
      dbr.exception(ex);
    }
  }
*/

  public static void main(String[] arg) throws Exception{
    new TryName();
  }

}
